<?php
/**
 * Author: Mr.Li<LHB2002@qq.com>
 * Date: 2018-04-26 11:56
 */
namespace happylhb\dictionary;
use \think\Db;

use \think\Controller;
use \think\Request;

class Dictionary extends Controller
{
    private $path='';
    private $database='';
    private $prefix = '';

    public function __construct(Request $request = null)
    {
        $this->database = Db::connect()->getConfig('database');
        $this->prefix = Db::connect()->getConfig('prefix');

        $this->path = __DIR__ .DIRECTORY_SEPARATOR. 'view'.DIRECTORY_SEPARATOR;
        parent::__construct($request);
    }


    public function index(){
        $data = Db::table('INFORMATION_SCHEMA.TABLES')
                    ->where('table_schema',$this->database)
                    ->field(['table_name','table_comment','engine'])
                    ->select();
        array_walk($data,function (&$val){
            $val['table_name'] = str_replace($this->prefix,'',$val['table_name']);
        });
        $this->view->assign('data',$data);
        return $this->view->fetch($this->path.'index.html');
    }

    public function table($name){
        $data = Db::table('INFORMATION_SCHEMA.COLUMNS')
                    ->where('table_schema',$this->database)
                    ->where('TABLE_NAME',$this->prefix . $name)
                    ->field(['column_name','column_comment','column_type','column_default','is_nullable','extra','column_key','column_key'])
                    ->order('ORDINAL_POSITION')
                    ->select();
        $this->view->assign('data',$data);

        $this->view->assign('table',$this->getTable($name));
        return $this->view->fetch($this->path.'table.html');
    }

    private function getTable($name){
        $info = Db::table('INFORMATION_SCHEMA.TABLES')
                ->where('table_schema',$this->database)
                ->where('table_name',$this->prefix .$name)
                ->field(['table_comment','engine'])
                ->find();
        $info['table_name'] = $name;

        return $info;
    }
}